<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router';
import type { articleData } from '@/utils/interface'
import { getArticleByIdApi } from '@/api/article_api'
import { getTime } from '@/utils/time';
import { useSubsetStore } from '@/stores/subset';
import { useSubset } from '@/hooks/subsetHook'
import { baseImgPath } from '@/utils/env'
import Comments from '@/components/comments/comments.vue'
const { getSubset } = useSubset()
const subsetStore = useSubsetStore();
const route = useRoute();
const id = computed<number>(() => Number(route.params.id));

const galleryDetail = ref<articleData>({
    id: 0,
    title: '',
    cover: '',
    created_at: new Date(),
    subset_id: 0,
    label: '',
    introduce: '',
    views: 0,
    comment: 0,
    praise: 0,
    state: 1,
    content: ''
})

const stringToArray = (str: string | undefined) => {
    return str?.split(",").map(item => item.trim());
}

// 解析图片字符串（处理空格和换行）
function parseImageStringRobust(str: string | undefined) {
    if (!str) return [];
    // 替换空格为逗号，使其成为有效的JSON数组
    const jsonArrayStr = `[${str.replace(/\}\s*\{/g, '},{')}]`;
    try {
        return JSON.parse(jsonArrayStr);
    } catch (error) {
        console.error('解析失败:', error);
        return [];
    }
}

const pictureArray = ref<any>([])
const urlArray = ref<any>([])
const getArticleDetail = async () => {
    const res = await getArticleByIdApi({ id: id.value })
    galleryDetail.value = res.data.data
    pictureArray.value = parseImageStringRobust(galleryDetail.value.content)
    urlArray.value = pictureArray.value.map((item:any) => baseImgPath + '/' + item.url)
    console.log('urlArray', urlArray.value);

    console.log('galleryDetail', galleryDetail.value);
}




onMounted(() => {
    getArticleDetail()
    getSubset(1)
})

</script>

<template>
    <div class="flex flex-col justify-center items-center">
        <!-- 封面区 -->
        <div class="w-full bg-linear-to-t from-purple-800 to-slate-800 text-white mb-5">
            <main class="min-h-[40vh] flex justify-center items-center w-full relative">
                <!-- 搜索区域 -->
            </main>
        </div>
        <!-- 标题区 -->
        <div class="max-w-[1200px] w-full bg-white p-5 mb-10">
            <!-- 顶部 -->
            <div class="max-w-[1200px] w-auto mb-10 flex justify-between">
                <!-- 标题时间 -->
                <div class="">
                    <h1 class="text-4xl font-bold">{{ galleryDetail.title }}</h1>
                    <p class="text-sm textColor-1">发布于{{ getTime(galleryDetail.created_at) }}</p>
                </div>
                <!-- 分类 -->
                <div class="text-lg font-bold">
                    {{ subsetStore.subsetName(galleryDetail.subset_id) }}
                </div>

            </div>
            <!-- 简介 -->
            <div class="max-w-[1200px] w-auto border-l-4 border-amber-400 bg-amber-50 px-10 py-5  rounded-xl mb-10">
                <p v-if="galleryDetail.introduce" class="extColor-1 leading-relaxed">
                    {{ galleryDetail.introduce }}
                </p>
                <p v-else class="textColor-1 leading-relaxed">
                    暂无简介
                </p>

            </div>
            <!-- 标签 -->
            <div>
                <div v-if="galleryDetail.label" v-for="(tag, index) in stringToArray(galleryDetail.label)" :key="tag"
                    :class="[
                        'inline-block px-2 py-1 rounded-lg textColor-1 text-sm mr-2',
                        index % 3 === 0 ? 'bg-sky-500/30' :
                            index % 3 === 1 ? 'bg-yellow-300/30' :
                                'bg-red-500/30'
                    ]">
                    {{ tag }}
                </div>
            </div>
        </div>
        <!-- 图片内容区 -->
        <div class="max-w-[1200px] w-full mb-10">
            <div class=" grid grid-cols-[repeat(auto-fill,minmax(280px,300px))] gap-5 justify-center">
                <div v-for="(item, index) in urlArray" :key="index" 
                     class="bg-white p-5 rounded-lg shadow-md h-[300px]">
                    <el-image :src="item" alt="" class="w-full h-full" :zoom-rate="1.2" :max-scale="7" 
                        :min-scale="0.2" :preview-src-list="urlArray" show-progress :initial-index="index" fit="cover">
                    </el-image>
                </div>
            </div>
        </div>
        <!-- 评论区 -->
        <div class="max-w-[1200px] w-full bg-white rounded-2xl shadow-2xl p-6  mb-5">
            <Comments :article_id="id" />
        </div>

    </div>
</template>

<style scoped></style>
